function! pg#fern#init() abort
    if bufname('%') =~# '^fern://drawer'
        call s:map_drawer_mode()
    endif
endfunction

function s:map_drawer_mode()
    nmap <buffer> <Plug>(fern-action-zoom:toggle) :call <SID>zoom_toggle()<cr>

    nnoremap <buffer> - <c-w>p
    nmap <buffer> R <Plug>(fern-action-reload)
    nmap <buffer> [ <Plug>(fern-action-leave)
    nmap <buffer><expr> ]
        \ fern#smart#leaf(
        \   "\<Plug>(fern-action-open:select)",
        \   "\<Plug>(fern-action-enter) \<Plug>(fern-wait) \<Plug>(fern-action-tcd:root)"
        \ )
    nmap <buffer> <cr> o
    nmap <buffer><expr> o
        \ fern#smart#leaf(
        \   "\<Plug>(fern-action-open:select)",
        \   "\<Plug>(fern-action-expand)",
        \   "\<Plug>(fern-action-collapse)"
        \ )
    nmap <buffer> m <Plug>(fern-action-mark)
    vmap <buffer> m <Plug>(fern-action-mark)
    nmap <buffer><expr> N
        \ fern#smart#leaf(
        \   "\<Plug>(fern-action-new-path)",
        \   "\<Plug>(fern-action-expand) \<Plug>(fern-wait) \<Plug>(fern-action-new-path)",
        \   "\<Plug>(fern-action-new-path)"
        \ )
    nmap <buffer> d <Plug>(fern-action-remove)
    nmap <buffer> r <Plug>(fern-action-rename)
    nmap <buffer> c <Plug>(fern-action-clipboard-copy)
    nmap <buffer> y <Plug>(fern-action-yank)
    nmap <buffer> p <Plug>(fern-action-clipboard-paste)
    nmap <buffer><expr> p
        \ fern#smart#leaf(
        \   "\<Plug>(fern-action-clipboard-paste)",
        \   "\<Plug>(fern-action-expand) \<Plug>(fern-wait) \<Plug>(fern-action-clipboard-paste)",
        \   "\<Plug>(fern-action-clipboard-paste)"
        \ )
    nmap <buffer> z <Plug>(fern-action-zoom:toggle)
    nmap <buffer> h <Plug>(fern-action-hidden)
    nmap <buffer> sp :call<SID>open_split()<cr>
endfunction

function! s:open_split() abort
    let fn = get(function('s:_split_complete_choice'), 'name')
    let dir = input('action: open:split:', '', printf('customlist,%s', fn))
    if index(s:_split_complete_choice(0, 0, 0), dir) >= 0
        call fern#action#call('open:'.dir)
    endif
endfunction

function! s:_split_complete_choice(arglead, cmdline, cursorpos) abort
    return ['above', 'below', 'top', 'bottom', 'left', 'right', 'leftest', 'rightest']
endfunction

function! s:zoom_toggle() abort
    if winwidth('$') <= 30
        call fern#action#call('zoom')
    else
        vertical resize 30
    endif
endfunction
